package com.fub.update;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageButton;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.fub.R;
import com.fub.update.BuildingUpdate.UpdateType;
import com.fub.util.PreferenceDAO;

public class UpdateActivity extends Activity {

	private static int PADDING = 10;
	private UpdateService updateService;
	private UpdateService.UpdateServiceBinder updateServiceBinder;
	private int currentUpdate = 0;
	private List<BuildingUpdate> updates;
	private Dialog prozessDialog;
	private Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.updates = new ArrayList<BuildingUpdate>();
		this.handler = new Handler();
		setContentView(R.layout.update);
		initUpdateServiceConnection();
	}

	private void addTextViewBuildingId(TableRow row, BuildingUpdate update) {
		TextView textViewBuildingId = createTextViews(update.getBuildingId());
		textViewBuildingId.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
		textViewBuildingId.setTextColor(Color.WHITE);
		row.addView(textViewBuildingId);
	}

	private void addTextViewUpdatetype(TableRow row, BuildingUpdate update) {
		TextView textViewUpdatetype = createTextViews(getFormatedUpdateType(update
				.getType()));
		row.addView(textViewUpdatetype);
	}

	private void addTextViewUpdateVersion(TableRow row, BuildingUpdate update) {
		TextView textViewUpdateVersion = createTextViews(update.getVersion()
				+ "");
		textViewUpdateVersion.setGravity(Gravity.CENTER);
		row.addView(textViewUpdateVersion);
	}

	private void addButton(TableRow row, BuildingUpdate update) {
		ImageButton btnImport = new ImageButton(this);
		btnImport.setBackgroundColor(Color.BLACK);
		Drawable image = getResources().getDrawable(R.drawable.download_icon);
		btnImport.setImageDrawable(image);
		btnImport.setPadding(PADDING, PADDING, PADDING, PADDING);
		btnImport.setOnClickListener(new OnClickListener() {
			int updateNr = UpdateActivity.this.currentUpdate;

			@Override
			public void onClick(View v) {
				UpdateActivity.this.updateService.updateOrAddNewBuilding(
						UpdateActivity.this.updates.get(this.updateNr),
						UpdateActivity.this);
			}
		});
		row.addView(btnImport);
	}

	private TextView createTextViews(String text) {
		TextView textView = new TextView(this);
		textView.setText(text);
		textView.setPadding(PADDING, PADDING, PADDING, PADDING);
		return textView;
	}

	private void initUpdateServiceConnection() {
		Intent intent = new Intent(getApplicationContext(), UpdateService.class);
		bindService(intent, new ServiceConnection() {
			@Override
			public void onServiceDisconnected(ComponentName name) {
			}

			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				UpdateActivity.this.updateServiceBinder = (UpdateService.UpdateServiceBinder) service;
				UpdateActivity.this.updateService = UpdateActivity.this.updateServiceBinder
						.getService();
				startGetBuildingVersionsThread();

			}
		}, BIND_AUTO_CREATE);
	}

	private void startGetBuildingVersionsThread() {
		showDialog(String.format("Hole Gebäudeversionen von Server %s",
				new PreferenceDAO(this).getServerName()));
		Thread thread = new Thread() {
			@Override
			public void run() {
				try {
					UpdateActivity.this.updates = UpdateActivity.this.updateService
							.getUpdates();
					UpdateActivity.this.handler
							.post(UpdateActivity.this.fillTable);
				} catch (IOException e) {
					UpdateActivity.this.handler
							.post(UpdateActivity.this.showErrorDialog);
				}

				UpdateActivity.this.handler
						.post(UpdateActivity.this.hideProcessDialog);

			}

		};
		thread.start();
	}

	private String getFormatedUpdateType(UpdateType type) {
		if (type == UpdateType.BUILDING_NEW) {
			return "Neues Gebäude";
		} else {
			return "Neues Update";
		}
	}

	private void showDialog(String text) {
		this.prozessDialog = ProgressDialog.show(this, "", text, true);
		this.prozessDialog.show();
	}

	private Runnable hideProcessDialog = new Runnable() {
		@Override
		public void run() {
			UpdateActivity.this.prozessDialog.hide();
		}
	};

	private Runnable showErrorDialog = new Runnable() {
		@Override
		public void run() {
			UpdateActivity.this.prozessDialog.hide();
			Toast.makeText(UpdateActivity.this,
					getResources().getString(R.string.connectionError),
					Toast.LENGTH_LONG).show();
		}
	};

	private Runnable fillTable = new Runnable() {
		@Override
		public void run() {
			fillTable();
		}
	};

	/**
	 * Fills the table layout with version informations of the buildings.
	 */
	private void fillTable() {
		TableLayout tl = (TableLayout) findViewById(R.id.updateTableLayout);
		for (BuildingUpdate update : this.updates) {
			TableRow row = new TableRow(this);
			addTextViewBuildingId(row, update);
			addTextViewUpdatetype(row, update);
			addTextViewUpdateVersion(row, update);
			addButton(row, update);
			tl.addView(row, new TableLayout.LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
			this.currentUpdate++;
		}
	}
}
